<?php

namespace app\index\controller;

use think\Controller;
use think\Facade\Request;
use app\index\model\Territory as Model;
class Territory extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $data =[];
        $warehouse  = Request::post('warehouse');
        $territoy = Model::where(['warehouse'=>$warehouse])
            ->field('title,points,driver_id,vehicle_id,router_title')
            ->select()
            ->toArray();
        foreach ( $territoy as $key=>$value)
        {
            $data[$value['title']] = isset( $data[$value['title']] ) ? $data[$value['title']] :[];
            $value['points'] = json_decode( $value['points'] , true );
            $title = $value['title'];
            $driver_id =  $value['driver_id'];
            $vehicle_id = $value['vehicle_id'];
            $data[$title]['points'][] = $value['points'];
            $data[$title]['title'] = $title;
            $data[$title]['driver_id'][] = $driver_id;
            $data[$title]['vehicle_id'][] = $vehicle_id;
            $data[$title]['router_title'][] = $value['router_title'];

        }
        returnAjax('200',$data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $post = Request::post();
        //清除久的数据
        $post['day'] = date('Y-m-d');
        $res = Model::create($post);
        if( $res )
        {
            returnAjax('200','SUCCESS');
        }
        returnAjax('201','Error');
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete()
    {
        $title = Request::post('title');
        $warehouse = Request::post('warehouse');
        Model::where(['title'=>$title,'warehouse'=>$warehouse])->delete();
        returnAjax('200','SUCCESS');   //一直返回200 否则更新队列更新失败

    }

    /**
     * territory是否存在
     */
    public function  isExist()
    {
        $tilte = Request::post('title');
        $has = Model::where(['title'=>$tilte])->count();
        if($has)
        {
            returnAjax('201','Title isexist');
        }else{
            returnAjax('200','Title invalid');
        }
    }
}
